# -*- coding: utf-8 -*-
from five import grok
from zope.interface import Interface
from Products.CMFCore.utils import getToolByName
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from plone.dexterity.interfaces import IDexterityContainer
from zope.component import getMultiAdapter
from zope.component import queryMultiAdapter
from OFS.interfaces import IOrderedContainer

class IGetTiraImgs(Interface):
    """Devuelve un diccionario con todas las imagenes de una carpeta"""
    def getTira(contexto):
        """devuelve un diccionario con los datos de las imagenes"""

    def getImagenDestacada(contexto):
        """devuelve un diccionario con la primera imagen de la carpeta"""

    def getExtraInfo(contexto):
        """Devuleve lista con los materiales para descargar que sean un File dentro del contenedor"""


class GetTiraImgs(grok.Adapter):
    grok.provides(IGetTiraImgs)
    grok.context(IDexterityContainer)

    def getExtraInfo(self):
        object=self.context
        catalog = getToolByName(object, 'portal_catalog')
        ruta	='/'.join(object.getPhysicalPath())
        results =catalog.searchResults({'portal_type': 'File', 'path':ruta})
        tira=[]


        for elem in results:
             obj=self.context.unrestrictedTraverse(elem.getPath())
             tira.append({
                    'url':          obj.absolute_url(),
                    'title':        obj.title,
                    'summary':      obj.description,
                    'position':     self.get_position_in_parent(obj),
                    'icono':        obj.getIcon(),
                    'fileSize':     obj.getObjSize(),
                    })

        if len(tira)>0:
            return sorted(tira, key=lambda k: k['position'])
        else:
            return None

    def getTira(self):
        object=self.context
        catalog = getToolByName(object, 'portal_catalog')
        ruta	='/'.join(object.getPhysicalPath())
        results =catalog.searchResults({'portal_type': ('Image','Link'),'path':ruta})
        tira=[]
        imgW=428



        for elem in results:
            flagOut=False
            objetoPosta=self.context.unrestrictedTraverse(elem.getPath())

            if elem.portal_type=="Link":
                ruta=elem.getRemoteUrl
                isLocal=ruta.find(self.context.portal_url())
                if isLocal==0:
                    listR=ruta.split("/")[3:]
                    objetoPosta=self.context.unrestrictedTraverse("/".join(listR))
                else:
                    flagOut=True



            if objetoPosta.portal_type in ('Image','Link') and not flagOut:
                objW=objetoPosta.width
                porcent=(imgW*100)/objW
                relH=(objetoPosta.height*porcent)/100

                tira.append({
                    'url':          objetoPosta.absolute_url(),
                    'title':        objetoPosta.Title(),
                    'summary':      objetoPosta.Description(),
                    'imageTag':     objetoPosta,
                    'imageTagGal':  objetoPosta,
                    'imgW':         imgW,
                    'imgH':         relH,
                    'position':     self.get_position_in_parent(objetoPosta)
                    })

        if len(tira)>0:
            return sorted(tira, key=lambda k: k['position'])
        else:
            return None


    def getImagenDestacada(self):
        result=self.getTira()
        if result:
            return result[:1]
        else:
            return None

    def get_position_in_parent(self,obj):
        """
        Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0

    def sort_by_position(self,a, b):
        """
        Python list sorter cmp() using position in parent.
        Descending order.
        """
        return self.get_position_in_parent(a) - self.get_position_in_parent(b)